using Autofac;
using Autofac.Extensions.DependencyInjection;
using BW.MesProject.BasicData.Application;
using BW.MesProject.BasicData.Infrastructure;
using BW.MesProject.Public.Infrastructure;
using System.Reflection;

namespace BW.MesProject.BasicData.Host
{
    /// <summary>
    /// Autofac依赖注入配置类
    /// </summary>
    public static class MyAutofac
    {
        /// <summary>
        /// 配置Autofac容器
        /// </summary>
        /// <param name="builder">WebApplicationBuilder实例</param>
        /// <returns>ConfigureContainer委托</returns>
        public static Action<ContainerBuilder> ConfigureAutofac(this WebApplicationBuilder builder)
        {
            return containerBuilder =>
            {
                // 注册仓储
                containerBuilder.RegisterGeneric(typeof(BaseRepository<>))
                    .As(typeof(IBaseRepository<>))
                    .InstancePerLifetimeScope();

                // 自动注册所有服务
                // 获取Application程序集中的所有服务实现类
                var serviceAssembly = Assembly.GetAssembly(typeof(WorkShopServices));
                // 获取Infrastructure程序集中的所有服务接口
                var interfaceAssembly = Assembly.GetAssembly(typeof(IWorkShopServices));

                if (serviceAssembly != null && interfaceAssembly != null)
                {
                    // 注册所有服务实现
                    containerBuilder.RegisterAssemblyTypes(serviceAssembly)
                        .Where(t => t.Name.EndsWith("Services"))
                        .AsImplementedInterfaces()
                        .InstancePerLifetimeScope();
                }
            };
        }
    }
} 